import { showFailToast, showSuccessToast } from 'vant'
import { render } from 'vue'
import DangerActionDialog from '~/components/common/DangerActionDialog.vue'
import DatePickerDialog from '~/components/common/DatePickerDialog.vue'
import TimePickerDialog from '~/components/common/TimePickerDialog.vue'
import _lodash from 'lodash'

export function renderVNode(comp: any, elId?: string) {
  let el: HTMLElement | null = null
  if (elId) {
    const _el = document.querySelector(`body>#${elId}`) as HTMLElement
    if (_el) {
      el = _el
    }
    else {
      el = document.createElement('div')
      el.id = elId
      document.body.appendChild(el)
    }
  }
  if (!el) {
    el = document.createElement('div')
    document.body.appendChild(el)
  }

  el.innerHTML = ''
  setTimeout(() => {
    console.log('render')

    render(comp, el!)
  })
}

export function backWhenSuccess(value: boolean) {
  if (value) {
    showSuccessToast('操作成功')
    setTimeout(() => {
      window.history.back()
    })
  }
  else {
    showFailToast('操作失败')
  }
}

export function protectedAction(
  dangerAction: () => void,
  reason = '你确定要进行该操作吗?',
  wait = 5,
) {
  const comp = h(DangerActionDialog, {
    dangerAction,
    wait,
    reason,
  })
  renderVNode(comp)
}

export async function pickDate(current?: Date): Promise<Date | undefined> {
  return new Promise((resolve) => {
    const comp = h(DatePickerDialog, {
      current,
      dateCb: resolve,
    })
    renderVNode(comp)
  })
}

export async function pickTime(current?: Date): Promise<Date | undefined> {
  return new Promise((resolve) => {
    const comp = h(TimePickerDialog, {
      current,
      dateCb: resolve,
    })
    renderVNode(comp)
  })
}

export const lodash = _lodash